//
//  LoginViewController.m
//  CoolTennisBall
//
//  Created by 谢伟康 on 15/12/14.
//  Copyright © 2015年 CoolLang. All rights reserved.
//

#import "LoginViewController.h"
#import "LoginService.h"
#import "MBProgressHUD+HudTools.h"
#import "UINavigationController+FDFullscreenPopGesture.h"
#import "NSBundle+CurrentLanguage.h"
#import "SLAbroadRegisterViewController.h"
#import "RetrievePasswordVC.h"


static NSString * const kUserInfoSegue = @"kUserInfoSegue";
static NSString * const kTabBarSegue   = @"kTabBarSegue";
static NSString * const kSignUpSegue = @"SignUpSegue";

static const NSInteger kPhoneNumCount = 11;

@interface LoginViewController ()<UITextFieldDelegate, UIGestureRecognizerDelegate, AbroadRegisterDelegate>

@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *varifyTextField;
@property (weak, nonatomic) IBOutlet UIButton *getVarifyBtn;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

@property (weak, nonatomic) IBOutlet UIButton *wechatBtn;
@property (weak, nonatomic) IBOutlet UILabel *weChatLabel;
@property (weak, nonatomic) IBOutlet UIView *weChatLeftView;
@property (weak, nonatomic) IBOutlet UIView *weChatRightView;
@property (weak, nonatomic) IBOutlet UIImageView *logoImageView;
@property (weak, nonatomic) IBOutlet UIButton *secretButton;
@property (weak, nonatomic) IBOutlet UIButton *signUpButton;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *weChatBtnCenterXCon;
@property (weak, nonatomic) IBOutlet UIButton *faceBookBtn;

@property (strong, nonatomic) LoginService *logService;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *facebookcenterXCon;

// 约束
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *secretBtnHeightCon;

@end

@implementation LoginViewController
{
    __weak FUIAlertView *_failAlertView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configureLocalization];
    [self registerNotification];
    [self customizeTextFields];
    [self showLaunchImage];
    
   
    if ([NSBundle currentLanguageIsChinese]) {
        self.weChatBtnCenterXCon.priority = 333;
        self.faceBookBtn.hidden = YES;
    }else {
        self.weChatBtnCenterXCon.priority = 999;
    }
    if (![self.logService isInstallWechat]) {
        self.wechatBtn.hidden = YES;
        if ([NSBundle currentLanguageIsChinese]) {
            self.weChatLabel.hidden = YES;
            self.weChatLeftView.hidden = YES;
            self.weChatRightView.hidden = YES;
        }else {
            self.facebookcenterXCon.priority = 333;
        }
    }else {
        self.facebookcenterXCon.priority = 999;
    }
    
    
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    if ([NSBundle currentLanguageIsChinese]) {
        self.phoneTextField.text = [User getLastUser].userInforItem.phoneNum;
        
    }else {
        self.phoneTextField.text = [User getLastUser].userInforItem.email;
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Localization

- (void)configureLocalization
{
    self.phoneTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"Login.Account", nil) attributes:@{
                                                                                                                                                 NSForegroundColorAttributeName: [UIColor colorWithWhite:1.0f alpha:0.8f]
                                                                                                                                                 }];
    
    self.varifyTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"Login.Varify", nil) attributes:@{
                                                                                                                                                       NSForegroundColorAttributeName: [UIColor colorWithWhite:1.0f alpha:0.8f]
                                                                                                                                                       }];
    self.weChatLabel.text = NSLocalizedString(@"Login.ThirdPart.Description", nil);
    if ([NSBundle currentLanguageIsChinese]) {
        self.signUpButton.hidden = YES;
        self.loginButton.hidden = YES;
        NSString *secretString = @"登录注册，表示您同意《服务条款及隐私政策》";
        
        NSAttributedString *attribute = [NSAttributedString attributedString:secretString subString:@[@"登录注册，表示您同意",@"《服务条款及隐私政策》"] colors:@[[UIColor whiteColor],kOrangeColor] fonts:@[[UIFont systemFontOfSize:11],[UIFont systemFontOfSize:11]]];
        [self.secretButton setAttributedTitle:attribute forState:UIControlStateNormal];
        self.secretBtnHeightCon.constant = 27.0;
      
    } else {
        [self.signUpButton setTitle:NSLocalizedString(@"Sign up", @"S'inscrire") forState:UIControlStateNormal];
        
        [self.loginButton setTitle:NSLocalizedString(@"Log in", @"S'identifier") forState:UIControlStateNormal];
        
        
        //[self.wechatBtn setImage:[UIImage imageNamed:@"login_icon_facebook"] forState:UIControlStateNormal];
//        self.secretButton.hidden = YES;
        NSString *forgotStr = NSLocalizedString(@"Forgot your password?", nil);
        NSAttributedString *attributedString = [NSAttributedString attributedString:forgotStr subString:@[forgotStr] colors:@[[UIColor whiteColor]] fonts:@[[UIFont systemFontOfSize:12]]];
        NSMutableAttributedString *attrStrM = [[NSMutableAttributedString alloc] initWithAttributedString:attributedString];
        [attrStrM addAttributes:@{NSUnderlineColorAttributeName:[UIColor whiteColor], NSUnderlineStyleAttributeName:@(NSUnderlineStyleSingle)} range:[forgotStr rangeOfString:forgotStr]];
        
        [self.secretButton setAttributedTitle:attrStrM.copy forState:UIControlStateNormal];
        self.secretBtnHeightCon.constant = 46.0;
        self.loginBtn.hidden = YES;
        self.getVarifyBtn.hidden = YES;
        
        self.phoneTextField.keyboardType = UIKeyboardTypeEmailAddress;
        self.varifyTextField.keyboardType = UIKeyboardTypeDefault;
        self.varifyTextField.secureTextEntry = YES;
        
    }
}

#pragma mark - Notification

- (void)registerNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleLoginFail) name:kNetworkingManagerLoginFailNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTextFieldChange) name:UITextFieldTextDidChangeNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(findPasswordCompleted:) name:@"FindPasswordCompleted" object:nil];
}

- (void)handleLoginFail {
    [DataModel setAutoLogin:NO];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)handleTextFieldChange {
    if (![NSBundle currentLanguageIsChinese] && self.phoneTextField.isFirstResponder) {
        self.phoneTextField.text = [self.phoneTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
}

- (void)findPasswordCompleted:(NSNotification *)note {
    self.phoneTextField.text = note.object;
}

#pragma mark - setter/getter

- (LoginService *)logService{
    if (!_logService) {
        self.logService = [[LoginService alloc] init];
    }
    return _logService;
}

#pragma mark - IBAction

- (IBAction)clickServiceAndPrivatePolicy:(id)sender {
    if ([NSBundle currentLanguageIsChinese]) {
       [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.coollang.com/appcontent/responsibility/?type=2"]];
    }else {
        // 找回密码入口
        RetrievePasswordVC *findPasswordVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"RetrievePasswordVC"];
        [self.navigationController pushViewController:findPasswordVC animated:YES];
    }
    
}

- (IBAction)phoneTextChange:(UITextField *)sender {
    BOOL isEleven = sender.text.length == kPhoneNumCount;
    BOOL isFour = self.varifyTextField.text.length == 4;
    
    if (isFour && isEleven) {
        
        self.loginBtn.backgroundColor = [UIColor colorWithHex:0x358F7F];
        self.loginBtn.enabled = YES;
    } else {
        self.loginBtn.backgroundColor = [UIColor colorWithHex:0x526A65];
        self.loginBtn.enabled = NO;
    }
}

- (IBAction)varifyTextChange:(UITextField *)sender {
    BOOL isFour = sender.text.length == 4;
    BOOL isEleven = self.phoneTextField.text.length == kPhoneNumCount;
    
    if (isFour && isEleven) {
        self.loginBtn.backgroundColor = [UIColor colorWithHex:0x358F7F];
        self.loginBtn.enabled = YES;
    } else {
        self.loginBtn.backgroundColor = [UIColor colorWithHex:0x526A65];
        self.loginBtn.enabled = NO;
    }
}

- (IBAction)loginByWeChat:(UIButton *)sender {
    if (sender.tag == 20) {
        // 微信登陆
        [self.logService loginByWeChatWithLoginByThirdPartPlatformBlock:^(BOOL successed, NSString *info ,BOOL isFirstLogin) {
            if (successed) {
                isFirstLogin ? [self performSegueWithIdentifier:kUserInfoSegue sender:nil] : [self performSegueWithIdentifier:kTabBarSegue sender:nil];
            } else {
                [self showShortInfo:info];
            }
        }];
    }else if (sender.tag == 21){
        // Facebook登陆
        [self.logService loginByFacebookWithLoginByThirdPartPlatformBlock:^(BOOL successed, NSString *info, BOOL isFirstLogin) {
            if (successed) {
                isFirstLogin ? [self performSegueWithIdentifier:kUserInfoSegue sender:nil] : [self performSegueWithIdentifier:kTabBarSegue sender:nil];
            } else {
                [self showShortInfo:info];
            }
        }];
    }
}


- (IBAction)getVarifyCode {
    if ([self.phoneTextField.text isEqualToString:@"13800138000"]) {
        [self showError:@"测试账号请直接输入验证码！"];
        return;
    }
    
    if (self.phoneTextField.text.length < kPhoneNumCount) {
        FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:NSLocalizedString(@"Reminder", nil) message:@"请输入正确的手机号码" delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"Yes", nil), nil];
        [alertView customizeAppearance];
        [alertView show];
        
        return;
    }
    
    __weak LoginViewController *weakSelf = self;
    if ([YFCheckNetworkStatus shareInstance].networkStatus == AFNetworkReachabilityStatusNotReachable) {
        [MBProgressHUD showTextHUDWithMessage:NSLocalizedString(@"Network unavailable, Check network", nil) inView:self.view];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        });
    }else {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        self.logService.varifyCodeblock = ^(BOOL successed,NSString *info ){
            if (successed) {
                [weakSelf inputVerifyCodeWithinSeconds:30];
            } else {
                [weakSelf showError:info];
            }
            
            [hud hideAnimated:YES];
        };
        
        [self.logService getSMSVarifyCode:self.phoneTextField.text];
    }
}

- (IBAction)loginByPhone {
    [self.phoneTextField resignFirstResponder];
    [self.varifyTextField resignFirstResponder];
   
    // 手机登陆
    
    if ([YFCheckNetworkStatus shareInstance].networkStatus == AFNetworkReachabilityStatusNotReachable) {
        FUIAlertView *alertView = [self.logService AlertViewWithTitle:NSLocalizedString(@"Reminder", nil) message:NSLocalizedString(@"Network unavailable, Check network", nil) cancelButtonTitle:@"OK"];
        [alertView show];
    }else {
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [self.logService loginByPhone:self.phoneTextField.text varifyNum:self.varifyTextField.text completeBlock:^(BOOL successed ,BOOL isFirstLogin) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if (successed) {
                if (self.phoneTextField.text.length > 0) {
                    self.phoneTextField.text = @"";
                    self.varifyTextField.text = @"";
                }
                isFirstLogin ? [self performSegueWithIdentifier:kUserInfoSegue sender:nil] : [self performSegueWithIdentifier:kTabBarSegue sender:nil];
                
            } else {
                [self showError:@"登录失败，请重新登录"];
            }
        }];
    }
}

- (IBAction)loginByEmail
{
    [self.phoneTextField resignFirstResponder];
    [self.varifyTextField resignFirstResponder];
    
    if (![self verifyEmail]) {
        FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:NSLocalizedString(@"Reminder", nil) message:NSLocalizedString(@"please enter a valid email address", nil) delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        
        [alertView customizeAppearance];
        [alertView show];
        
        return;
    }
    if (![self verifyPassword]) {
        NSString *tipStr = NSLocalizedString(@"Passwords should be a combination of 6-16 letters, numbers and underscores", nil);
        FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:NSLocalizedString(@"Reminder", nil) message:tipStr delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertView customizeAppearance];
        [alertView show];
        
        return;
    }
    
    
    
    if ([YFCheckNetworkStatus shareInstance].networkStatus == AFNetworkReachabilityStatusNotReachable) {
        FUIAlertView *alertView = [self.logService AlertViewWithTitle:NSLocalizedString(@"Reminder", nil) message:NSLocalizedString(@"Network unavailable, Check network", nil) cancelButtonTitle:@"OK"];
        [alertView show];
    }else {
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        // 邮箱登陆
        [self.logService loginByEmail:self.phoneTextField.text password:self.varifyTextField.text completionBlock:^(BOOL successed, BOOL isFirstLogin) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if (successed) {
                isFirstLogin ? [self performSegueWithIdentifier:kUserInfoSegue sender:nil] : [self performSegueWithIdentifier:kTabBarSegue sender:nil];
                if (self.phoneTextField.text.length > 0) {
                    self.phoneTextField.text = @"";
                    self.varifyTextField.text = @"";
                }
            } else {
                [self showError:NSLocalizedString(@"Log on invalid,please log in again", nil)];
            }
        }];
    }
}

- (BOOL)verifyEmail{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailVerify = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailVerify evaluateWithObject:self.phoneTextField.text];
}

- (BOOL)verifyPassword{
    NSString *passwordRegex = @"^[a-zA-Z0-9_-]{6,16}$";
    NSPredicate *passwordVerify = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passwordRegex];
    return [passwordVerify evaluateWithObject:self.varifyTextField.text];
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([segue.identifier isEqualToString:kUserInfoSegue]) {
        self.navigationController.navigationBarHidden = YES;
    } else if ([segue.identifier isEqualToString:kTabBarSegue]){
        [DataModel setAutoLogin:YES];
    } else if ([segue.identifier isEqualToString:kSignUpSegue]) {
        SLAbroadRegisterViewController *controller = segue.destinationViewController;
        controller.delegate = self;
    }
}

- (IBAction)hideKeyboard:(UITapGestureRecognizer *)sender
{
    if ([self.phoneTextField isFirstResponder]) {
        [self.phoneTextField resignFirstResponder];
    } else if ([self.varifyTextField isFirstResponder]) {
        [self.varifyTextField resignFirstResponder];
    }
}

#pragma mark - UIGestureRecognizerDelegate

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    return touch.view == self.logoImageView || touch.view == self.view;
}

#pragma mark - Private Method

- (void)showLaunchImage
{
    UIImageView *launchImageView = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    launchImageView.image = [UIImage imageNamed:NSLocalizedString(@"launchBackground_en", nil)];
    [self.view addSubview:launchImageView];
    
    [UIView animateWithDuration:0.35 delay:1.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        launchImageView.alpha = 0;
    } completion:^(BOOL finished) {
        [launchImageView removeFromSuperview];
        [self checkAccountShouldAutoLogin];
    }];
}


- (void)customizeTextFields
{
    self.phoneTextField.tintColor = [UIColor whiteColor];
    self.varifyTextField.tintColor = [UIColor whiteColor];
}

#pragma mark - AutoLogin
- (void)checkAccountShouldAutoLogin
{
    if ([DataModel shouldAutoLogin]) {
        [[YFNetworkingService sharedInstance] sendRequest:[YFLoginApi refreshLoginApi] callback:^(BOOL success, id result, NSError *error) {
            if (success) {
                
            }
        }];
        [self performSegueWithIdentifier:kTabBarSegue sender:nil];
    } else {
        
    }
}

#pragma mark - showErrorInfo/reminder

- (void)showError:(NSString *)error{
    
    if (_failAlertView == nil) {
        FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:NSLocalizedString(@"Reminder", nil) message:error delegate:nil cancelButtonTitle:NSLocalizedString(@"Yes", nil) otherButtonTitles:nil];
        [alertView customizeAppearance];
        [alertView show];
        _failAlertView = alertView;
    }
}

- (void)showShortInfo:(NSString *)info{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [hud showTextHUDWithMessage:info inView:self.view];
}

#pragma mark - UITextDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([NSBundle currentLanguageIsChinese]) {
        NSInteger kPhoneValidLength = kPhoneNumCount;
        NSInteger kVerifyCodeValiedLength = 4;

        NSString *newText = [textField.text stringByReplacingCharactersInRange:range withString:string];
        
        // 手机号码不能超过11位
        if ([textField isEqual:self.phoneTextField]) {
            
            if (newText.length > kPhoneValidLength) {
                return NO;
            }
            // 验证码不能超过4位
        } else if ([textField isEqual:self.varifyTextField]) {
            
            if (newText.length > kVerifyCodeValiedLength) {
                return NO;
            }
            
        }
    }     
    return YES;
}

- (void)inputVerifyCodeWithinSeconds:(NSUInteger)seconds
{
    __block NSInteger blockSecond = seconds;
    [self refreshVerifyCodeRemainSeconds:seconds];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        blockSecond--;
        if (blockSecond > 0) {
            [self inputVerifyCodeWithinSeconds:blockSecond];
        } else {
            [self refreshGetVariyCodeBtn];
        }
    });
}

- (void)refreshVerifyCodeRemainSeconds:(NSUInteger)seconds
{
    self.getVarifyBtn.enabled = NO;
    [self.getVarifyBtn setTitle:[NSString stringWithFormat:@"%lu秒", (unsigned long)seconds] forState:UIControlStateDisabled];
}

- (void)refreshGetVariyCodeBtn{
    self.getVarifyBtn.enabled = YES;
    [self.getVarifyBtn setTitle:@"重新获取" forState:UIControlStateNormal];
}

-(BOOL)fd_prefersNavigationBarHidden {
    return YES;
}

#pragma mark - AbroadRegisterDelegate

- (void)registerFinish:(NSString *)email password:(NSString *)password
{
    self.phoneTextField.text = email;
    self.varifyTextField.text = password;
    
    [self loginByEmail];
}

@end
